package com.snail.commonlibrary;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.widget.Toast;

import java.util.List;

/**
 * 短信操作相关工具类
 * Created by zhaoys on 2015/9/6.
 */
public class SMSUtils {
   // public SMSUtils(Context pcontext) {
     //   context = pcontext;
    //}

    /**
     * 直接调用发短信接口
     *
     * @param phoneNumber
     * @param message
     */
    public static void sendSMS(String phoneNumber, String message,final Context context) {

        //处理返回的发送状态
        String SENT_SMS_ACTION = "SENT_SMS_ACTION";
        Intent sentIntent = new Intent(SENT_SMS_ACTION);
        PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, sentIntent, 0);
        // register the Broadcast Receivers
        context.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context _context, Intent _intent) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(context,
                                "短信发送成功", Toast.LENGTH_SHORT)
                                .show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        break;
                }
            }
        }, new IntentFilter(SENT_SMS_ACTION));


        //处理返回的接收状态
        String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
        // create the deilverIntent parameter
        Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
        PendingIntent deliverPI = PendingIntent.getBroadcast(context, 0, deliverIntent, 0);
        context.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context _context, Intent _intent) {
                Toast.makeText(context, "收信人已经成功接收", Toast.LENGTH_SHORT).show();
            }
        }, new IntentFilter(DELIVERED_SMS_ACTION));


        //获取短信管理器
        SmsManager smsManager = SmsManager.getDefault();
        if (message.length() > 70) {
            //拆分短信内容（手机短信长度限制）
            List<String> contents = smsManager.divideMessage(message);
            for (String sms : contents) {
                smsManager.sendTextMessage(phoneNumber, null, sms,sentPI, deliverPI);
            }
        } else {
            smsManager.sendTextMessage(phoneNumber, null, message,sentPI, deliverPI);
        }
    }
}
